var isNew = "0";
var TableEditable = function () {

    return {
        //main function to initiate the module
        init: function () {

            function restoreRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);
                var lblId = jqTds.find("label[for=id]");
                var id = lblId.text();
                if (id != '') {
                    for (var i = 0, iLen = jqTds.length; i < iLen; i++) {

                        oTable.fnUpdate(aData[i], nRow, i, false);
                    }
                    oTable.fnDraw();
                }
                else {
                    oTable.fnDeleteRow(nRow);
                }
            }
            function editRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);
                jqTds[0].innerHTML = '<input type="text" class="m-wrap span4" value="' + aData[0] + '">';
                if (aData[0] == "") {
                    jqTds[1].innerHTML = '<select  class="filter"></select>';
                    $.ajax({
                        type: "POST",
                        url: "FilterDetail-List.aspx/GetFilter",
                        data: "{}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            $.each(response.d, function (key, value) {
                                jqTds.find(".filter").append($("<option></option>").val
                                    (value.Id).html(value.Name));
                            });
                        },
                        failure: function (response) {
                            alert(response.d);
                        }
                    }
                                );
                }
                else
                    jqTds[1].innerHTML = '<span class="sFilter">' + aData[1] + '</span>';

                jqTds[2].innerHTML = '<a class="edit" href="">Save</a>';
                jqTds[3].innerHTML = '<a class="cancel" href="">Cancel</a>';

            }
            function saveRow(oTable, nRow) {

                var jqInputs = $('input', nRow);
                var jqSpan = $('span', nRow);
                var jqTds = $('>td', nRow);

                var name = jqInputs[0].value;
                var filterid = "0";
                var filtername = "";
                nEditing = nRow;
                if (name == "") {
                    DisplayMessage('<strong>Error! </strong>Please Enter Feature Detail.', 'alert alert-danger');
                    $('.name').css("border", "1px solid red");
                    return;
                }
                var lblId = jqTds.find("label[for=id]");
                var lblFilterId = jqTds.find("label[for=filterid]");
                var id = lblId.text();

                if (id == "") {

                    filterid = $(".filter option:selected").val();
                    filtername = $(".filter option:selected").text();
                }
                else {
                    filterid = lblFilterId.text();

                    filtername = jqTds[1].innerHTML;
                }

                $.ajax({
                    type: "POST",
                    url: "FilterDetail-List.aspx/Update",
                    data: '{name: "' + name + '",id:"' + id + '" ,filterid:"' + filterid + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {

                        if (response.d == "0") {
                            ret = "false";
                            DisplayMessage('<strong>Error! </strong>Feature Datail is already exits...', 'alert alert-danger');
                           
                        }
                        else {
                            ret = "true";
                            oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
                            oTable.fnUpdate(filtername, nRow, 1, false);
                            oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 2, false);
                            oTable.fnUpdate('<a class="delete" href="">Delete</a>', nRow, 3, false);
                            oTable.fnUpdate('<label for="id" style="display:none">' + response.d + '</label>' + '<label for="filterid" style="display:none">' + filterid + '</label>', nRow, 4, false);

                            if (id == "")
                                DisplayMessage('<strong>Success! </strong>Feature Detail is Added Successfully.', 'alert alert-success');
                            else
                                DisplayMessage('<strong>Success! </strong>Feature Detail Updated Successfully.', 'alert alert-success');
                        }
                    },
                    failure: function (response) {
                        alert(response.d);
                    }
                }

            );
                isNew = 0;
            }
            function cancelEditRow(oTable, nRow) {

                var jqInputs = $('input', nRow);
                oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);

                // alert(nRow);
                oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 1, false);
                oTable.fnDraw();
                isNew = 0;
            }

            var oTable = $('#sample_editable_1').dataTable({
                "aLengthMenu": [
                    [5, 15, 20, -1],
                    [5, 15, 20, "All"] // change per page values here
                ],
                // set the initial value
                "iDisplayLength": 15,
                "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
                "sPaginationType": "bootstrap",
                "oLanguage": {
                    "sLengthMenu": "_MENU_ records per page",
                    "oPaginate": {
                        "sPrevious": "Prev",
                        "sNext": "Next"
                    }
                },
                "aoColumnDefs": [{
                    'bSortable': false,
                    'aTargets': [0]
                }
                ]
            });

            jQuery('#sample_editable_1_wrapper .dataTables_filter input').addClass("m-wrap medium"); // modify table search input
            jQuery('#sample_editable_1_wrapper .dataTables_length select').addClass("m-wrap small"); // modify table per page dropdown
            jQuery('#sample_editable_1_wrapper .dataTables_length select').select2({
                showSearchInput: false //hide search box with special css class
            }); // initialize select2 dropdown

            var nEditing = null;

            $('#sample_editable_1_new').click(function (e) {

                if (isNew == "0") {

                    e.preventDefault();
                    var aiNew = oTable.fnAddData(['', '', '', '', '',
                        ''
                ]);
                    var nRow = oTable.fnGetNodes(aiNew[0]);
                    editRow(oTable, nRow);
                    nEditing = nRow;
                    isNew = "1";
                }
                else {
                    return false;
                }
            });

            $('#sample_editable_1 a.delete').live('click', function (e) {
                e.preventDefault();
                if (confirm("Are you sure to delete this row ?") == false) {
                    return;
                }
                var nRow = $(this).parents('tr')[0];
                var jqTds = $('>td', nRow);


                var name = jqTds[0].innerHTML;
                var lblId = jqTds.find("label[for=id]");
                var id = lblId.text();

                $.ajax({
                    type: "POST",
                    url: "FilterDetail-List.aspx/Delete",
                    data: '{id:"' + id + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {

                        if (response.d == "error") {
                            ret = "false";
                            nEditing = nRow;

                            //  alert('You can not delete this filter because it is used by another page..');
                            DisplayMessage('<strong>Error! </strong>You can not delete this Feature Detail because it is used by another page..', 'alert alert-danger');

                        }
                        else {
                            oTable.fnDeleteRow(nRow);
                            DisplayMessage('<strong>Success! </strong>Feature Detail is Deleted Successfully.', 'alert alert-success');
                        }
                    },
                    failure: function (response) {
                        alert(response.d);
                    }
                }
            );
                isNew = 0;
                //alert("Deleted! Do not forget to do some ajax to sync with backend :)");
            });

            $('#sample_editable_1 a.cancel').live('click', function (e) {

                e.preventDefault();
                var nRow = $(this).parents('tr')[0];
                if ($(this).attr("data-mode") == "new") {
                    var nRow = $(this).parents('tr')[0];
                    oTable.fnDeleteRow(nRow);
                } else {

                    restoreRow(oTable, nRow);
                    nEditing = null;
                }
                isNew = 0;
            });
            $('#sample_editable_1 a.edit').live('click', function (e) {
                e.preventDefault();


                /* Get the row as a parent of the link that was clicked on */
                var nRow = $(this).parents('tr')[0];

                if (nEditing !== null && nEditing != nRow) {

                    /* Currently editing - but not this row - restore the old before continuing to edit mode */
                    restoreRow(oTable, nEditing);
                    editRow(oTable, nRow);
                    nEditing = nRow;
                } else if (this.innerHTML == "Save") {

                    nEditing = nRow;
                    /* Editing this row and want to save it */
                    saveRow(oTable, nEditing);
                    nEditing = null;

                    //alert("Updated! Do not forget to do some ajax to sync with backend :)");
                } else {

                    /* No edit in progress - let's start one */
                    editRow(oTable, nRow);
                    nEditing = nRow;
                }
            });
        }

    };

} ();
